#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
将 annotations.json 转换为 check_zone 可用的输入格式
- 读取 annotations.json
- 读取 lesion 描述字典 med_lesion_description.json
- 将归一化坐标 bbox 转换为像素坐标
- 输出 merged_annotations.json
"""

import os
import json
from PIL import Image

def convert_annotations(ann_path, lesion_desc_path, orignal_dir, output_json):
    with open(lesion_desc_path, "r", encoding="utf-8") as f:
        lesion_desc = json.load(f)
    with open(ann_path, "r", encoding="utf-8") as f:
        anns = json.load(f)

    out_list = []

    for fname, meta in anns.items():
        rel_path = meta["image_rela_dir"]
        orig_path = os.path.join(orignal_dir, rel_path)
        if not os.path.exists(orig_path):
            print(f"[WARN] 原图缺失: {orig_path}")
            continue

        try:
            with Image.open(orig_path) as img:
                W, H = img.size
        except Exception as e:
            print(f"[ERROR] 打开失败: {orig_path}, {e}")
            continue

        entry = {
            "image_path": orig_path,   # 这里后续可以改成224预处理图的路径
            "bboxes": [],
            "meta": {
                "original_path": orig_path,
                "crop_info": {
                    "crop_box": [0, H, 0, W],
                    "original_size": [H, W],
                    "cropped_size": [224, 224],
                }
            }
        }

        for lesion in meta.get("lesions", []):
            name = lesion["name"]
            desc = lesion_desc.get(name, f"病灶: {name}")
            x1, y1, x2, y2 = lesion["bbox"]

            # 映射到 224×224
            xyxy = [
                int(round(x1 * 224)),
                int(round(y1 * 224)),
                int(round(x2 * 224)),
                int(round(y2 * 224)),
            ]

            entry["bboxes"].append({
                "xyxy": xyxy,
                "description": desc,
            })

        if entry["bboxes"]:
            out_list.append(entry)

    with open(output_json, "w", encoding="utf-8") as f:
        json.dump(out_list, f, ensure_ascii=False, indent=2)

    print(f"[INFO] 共 {len(out_list)} 张，已保存 {output_json}")



if __name__ == "__main__":
    ann_path = "/home/zhangpinglu/data0/gy/Dataset/aier_processed/annotations.json"
    lesion_desc_path = "/home/zhangpinglu/data0/gy/code/fundus-reasoner-adaptive/fundus_reasoner/data_preprocess/configs/med_lesion_description.json"
    orignal_dir = "/home/zhangpinglu/data0/gy/Dataset/aier_orignal"
    output_json = "./experiments/aier_data_annotations.json"

    convert_annotations(ann_path, lesion_desc_path, orignal_dir, output_json)
